// ==UserScript==
// @name           EnQuest: Stats Export
// @namespace      enquest
// @autor          Rahman
// @version        1.0
// @description    Special dialog for exporting game stats into CSV
// @include        http://*.en.cx/GameStat.aspx?*
// @include        http://*.encounter.cx/GameStat.aspx?*
// @include        http://*.encounter.ru/GameStat.aspx?*
// @include        http://*.en-world.org/GameStat.aspx?*
// @include        http://quest.ua/GameStat.aspx?*
// @include        http://*.quest.ua/GameStat.aspx?*
// ==/UserScript==

(function ($) {
	$.ENQUEST.STAT = {
		ready:	false,
		dialog:	$('<div class="enPnl1 border_rad5" style="padding:4px; width:500px; height:400px; position:absolute; z-index:1000; -moz-box-shadow:2px 2px 5px #666666; display:none;"><div id="export_teams" style="width:40%; height:60%; overflow:auto; float:left;"></div><div id="export_levels"  style="width:60%; height:60%; overflow:auto; float:right;"></div><textarea id="csv" style="clear:both; width:99%; height:38.5%;" wrap="off"></textarea></div>').appendTo(document.body),
		
		levels:	[],
		teams:	{},
		
		getLevelTeam: function(td) {
			var result	= null;
			
			var team =  $(td).find('a[href*="TeamDetails.aspx"]');
			
			if(team.length == 1) {
				// Team game
				result = {
					'name':		team.text(),
					'id':		team.get(0).href.match(/^.*tid=(\d+)$/i)[1]
				}
			} else {
				// Personal game
				var user = $(td).find('a[href*="UserDetails.aspx"]');
				result = {
					'name':		user.text(),
					'id':		user.get(0).href.match(/^.*uid=(\d+)$/i)[1]
				}
			}
			
			return result;
		},
		
		parse:	function() {
			// Levels' names array
			var levels_html = [];
			$('table.DataTable tr.levelsRow:first td').each(function() {
				var td = $(this);
				if(!(td.find('div.spacer').length > 0 || td.hasClass('totalRowHead'))) {
					$.ENQUEST.STAT.levels.push(td.text());
					levels_html.push('<label><input type="checkbox" value="' + ($.ENQUEST.STAT.levels.length - 1) + '" name="export_levels">' + td.text() + '</label>');
				}
			});
			$.ENQUEST.STAT.dialog.find('#export_levels').html(levels_html.join('<br />\n'));
			
			// Teams array
			var teams_html = [];
			$('table.DataTable tr[class!=levelsRow]').find('td.totalCell:last').each(function() {
				var team	= $.ENQUEST.STAT.getLevelTeam(this);
				
				if(team) {
					$.ENQUEST.STAT.teams[team.id] = {
						name:	team.name,
						times:	[],
						total:	0
					};
					
					teams_html.push('<label><input type="checkbox" value="' + team.id + '" name="export_teams">' + team.name + '</label>');
				}
			});
			$.ENQUEST.STAT.dialog.find('#export_teams').html(teams_html.join('<br />\n'));
			
			// Analize levels
			$('table.DataTable tr[class!=levelsRow]').each(function() {
				var level = 0;
				$(this).find('div.dataCell').each(function() {
					var team = $.ENQUEST.STAT.getLevelTeam(this)
					
					if(team) {
						var text = $(this).text().replace(/\s+ч\.\s*/, ':').replace(/\s+м\.\s*/, ':').replace(/\s+с\.\s*/, '');
						var matched = text.match(/\(([\d\:]+)\)/);
						
						if(matched && matched[1]) {
							var s	= matched[1].split(':'), time;
							switch(s.length) {
								case 1:
									time = '0:00:' + (parseInt(s[0])||0);
									break;
									
								case 2:
									time = '0:' + (parseInt(s[0])||0) + ':' + (parseInt(s[1])||0);
									break;
									
								case 3:
									time = (parseInt(s[0])||0) + ':' + (parseInt(s[1])||0) + ':' + (parseInt(s[2])||0);
									break;
							}
							
							$.ENQUEST.STAT.teams[team.id].times[level] = time;
						}
					}
					
					level++;
				});
			});

			$.ENQUEST.STAT.dialog.find('input:checkbox').click(function() {
				var selected_teams = [], selected_levels = [];
				
				$.ENQUEST.STAT.dialog.find('input[name=export_levels]').each(function() {
					if($(this).attr('checked')) selected_levels.push(parseInt($(this).val()));
				});
				
				$.ENQUEST.STAT.dialog.find('input[name=export_teams]').each(function() {
					if($(this).attr('checked')) selected_teams.push(parseInt($(this).val()));
				});
				
				var csv = [];
				
				var title = ['#'];
				for(var i=0; i<$.ENQUEST.STAT.levels.length; i++) {
					if(selected_levels.indexOf(i) >= 0) title.push($.ENQUEST.STAT.levels[i])
				}
				
				csv.push(title);
				
				$.each($.ENQUEST.STAT.teams, function(tid, team) {
					tid = parseInt(tid);
					if(selected_teams.indexOf(tid) >= 0) {
						var line = [team.name];
						for(var i=0; i<team.times.length; i++) {
							if(selected_levels.indexOf(i) >= 0) line.push(team.times[i]);
						}
						csv.push(line);
					}
				});
				
				for(var i=0; i<csv.length; i++) {
					csv[i] = csv[i].join(';');
				}
				
				$.ENQUEST.STAT.dialog.find('textarea').val(csv.join('\n'));
			});

			$.ENQUEST.STAT.ready = true;
		},
		
	};

	$('a[href*="GameStat.aspx?sortfield=LevelSpent"]')
		.after($('<a class="lm" href="javascript:void(0);">экспорт статистики</a>').click(function() {
			if($.ENQUEST.STAT.ready != true) $.ENQUEST.STAT.parse();
																								   
			var position = $(this).position();
			$.ENQUEST.STAT.dialog.css({
				'left':	position.left - 4,
				'top':	position.top + 16,
			}).toggle();
		}))
		.after('&nbsp;|&nbsp;');

})(unsafeWindow.jQuery);